﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Office.Interop.Outlook;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Outlook.WorkItems.Extension.Controls;

namespace Outlook.WorkItems.Extension.Addin.Forms
{
    internal partial class SelectWorkItemForm : Form
    {
        private readonly WorkItemStore workItemStore;


        public string FileName
        {
            get { return null; }
        }

        public OlSaveAsType FileFormat
        {
            get { return OlSaveAsType.olTXT; }
        }

        public WorkItem SelectedWorkItem
        {
            get
            {
                int[] selectedIds = workItemResultGrid1.GetSelectedIds();
                if (selectedIds != null && selectedIds.Count() > 0)
                {
                    WorkItem wi = workItemStore.GetWorkItem(selectedIds[0]);
                    return wi;
                }
                return null;
            }
        }

        public bool AddMailAttachments
        {
            get { return false; }
        }

        public SelectWorkItemForm()
        {
            InitializeComponent();
        }

        public SelectWorkItemForm(WorkItemStore store, string projectName, string emailSubject)
            : this()
        {
            workItemStore = store;

            //txtFileName.Text = emailSubject;
            comboTree1.InitCombo();

            try
            {
                if (!string.IsNullOrEmpty(Properties.Settings.Default.SelectedQuery) && Properties.Settings.Default.SelectedQuery.Contains("#"))
                {
                    var selectedQueryParam = Properties.Settings.Default.SelectedQuery;
                    var selectedQueryParams = selectedQueryParam.Split('#');
                    if (selectedQueryParams.Length != 3)
                        return;

                    var serverUri = selectedQueryParams[0];
                    projectName = selectedQueryParams[1];
                    var queryId = new Guid(selectedQueryParams[2]);

                    var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUri));
                    store = tfs.GetService<WorkItemStore>();
                    var p = store.Projects[projectName];

                    var item = p.QueryHierarchy.Find(queryId);
                    if (item != null && item is QueryDefinition)
                    {
                        var selectedQuery = (QueryDefinition)item;
                        var node = comboTree1.m_trvNodes.Nodes.FindNodes(
                            tn => tn is QueryNode && ((QueryNode)tn).TeamQuery.Id == queryId).FirstOrDefault();

                        comboTree1.Text = node != null ? node.FullPath : string.Format("{0}/{1}", tfs.Name, selectedQuery.Path);

                        ExecuteQuery(selectedQuery);
                    }
                }
            }
            catch { }
        }

        public SelectWorkItemForm(WorkItemStore store, string projectName)
            : this()
        {
            
            workItemStore = store;

            //txtFileName.Text = emailSubject;
            comboTree1.InitCombo(store.TeamProjectCollection.Uri.ToString(), projectName);

            try
            {
                if (!string.IsNullOrEmpty(Properties.Settings.Default.SelectedQuery) && Properties.Settings.Default.SelectedQuery.Contains("#"))
                {
                    var selectedQueryParam = Properties.Settings.Default.SelectedQuery;
                    var selectedQueryParams = selectedQueryParam.Split('#');
                    if (selectedQueryParams.Length != 3)
                        return;

                    var serverUri = selectedQueryParams[0];
                    projectName = selectedQueryParams[1];
                    var queryId = new Guid(selectedQueryParams[2]);

                    var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUri));
                    store = tfs.GetService<WorkItemStore>();
                    var p = store.Projects[projectName];

                    var item = p.QueryHierarchy.Find(queryId);
                    if (item != null && item is QueryDefinition)
                    {
                        var selectedQuery = (QueryDefinition)item;
                        var node = comboTree1.m_trvNodes.Nodes.FindNodes(
                            tn => tn is QueryNode && ((QueryNode)tn).TeamQuery.Id == queryId).FirstOrDefault();

                        comboTree1.Text = node != null ? node.FullPath : string.Format("{0}/{1}", tfs.Name, selectedQuery.Path);

                        ExecuteQuery(selectedQuery);
                    }
                }
            }
            catch { }
        }

        private Query GetQuery(string storedQueryText, Hashtable context)
        {
            return new Query(workItemStore, storedQueryText, context);
        }

        private void ExecuteQuery(QueryDefinition queryDefinition)
        {
            var context = new Hashtable();

            Query query;

            if (queryDefinition != null)
            {
                context.Add("project", queryDefinition.Project.Name);
                query = GetQuery(queryDefinition.QueryText, context);
                workItemResultGrid1.LoadFromQuery(query);
                var wis = new List<WorkItem>();
                switch (queryDefinition.QueryType)
                {
                    case QueryType.List:
                        WorkItemCollection wicol = query.RunQuery();
                        wis.AddRange(wicol.Cast<WorkItem>());
                        break;
                    case QueryType.OneHop:
                    case QueryType.Tree:
                        WorkItemLinkInfo[] info = query.RunLinkQuery();
                        wis.AddRange(info.Select(item => workItemStore.GetWorkItem(item.TargetId)));
                        break;
                    default:
                        break;
                }
            }
            else
                return;
        }

        private void SelectWorkItemForm_Load(object sender, EventArgs e)
        {
        }

        private void workItemResultGrid1_SelectionChanged(object sender, EventArgs e)
        {
            var ids = workItemResultGrid1.GetSelectedIds();
            btnOk.Enabled = ids != null && ids.Count() == 1;
        }

        private void comboTree1_DropDown(object sender, EventArgs e)
        {
            comboTree1.ExpandPath();
        }

        void comboTree1_NodeSelected(object sender, TreeViewEventArgs e)
        {
            var node = comboTree1.m_trvNodes.SelectedNode;
            if (!(node is QueryNode)) 
                return;

            var queryNode = node as QueryNode;
            var selectedQuery = queryNode.TeamQuery;
            ExecuteQuery(selectedQuery);
        }
    }

    public class FormatMail
    {
        private OlSaveAsType m_format;
        private string m_text;

        public FormatMail(OlSaveAsType format, string text)
        {
            m_format = format;
            m_text = text;
        }

        public OlSaveAsType Format
        {
            get { return m_format; }
        }

        public override string ToString()
        {
            return m_text;
        }
    }
}
